package com.zjuh.qss.web.action;

import javax.servlet.http.HttpSession;

import wint.help.biz.result.Result;
import wint.help.mvc.DefaultSessionKeys;
import wint.help.mvc.WebConstants;
import wint.lang.utils.StringUtil;
import wint.mvc.flow.FlowData;
import wint.mvc.form.Form;
import wint.mvc.module.annotations.Action;
import wint.mvc.template.Context;

import com.zjuh.qss.biz.ao.UserAO;
import com.zjuh.qss.biz.domain.UserDO;
import com.zjuh.qss.web.common.BaseAction;

public class User extends BaseAction {
	
	private UserAO userAO;
	
	private String defaultTarget = "admin/index";
	
	private String defaultModule = "baseModule";
	
	private String loginTarget = "login";
	
	@Action(defaultTarget="login")
	public void doLogin(FlowData flowData, Context context) {
		Form form = flowData.getForm("user.login");
		UserDO userDO = new UserDO();
		if (!form.apply(userDO)) {
			return;
		}
		Result result = userAO.handleLogin(userDO);
		if (result.isSuccess()) {
			UserDO resultUser = (UserDO)result.getModels().get("user");
			applyUserLogin(flowData, resultUser);
			redirectForRequest(flowData);
		} else {
			this.handleError(result, flowData, context);
		}
	}
	
	public void doLogout(FlowData flowData, Context context) {
		dropUserLogin(flowData);
		flowData.redirectTo(defaultModule, loginTarget);
	}
	
	protected void dropUserLogin(FlowData flowData) {
		HttpSession session = flowData.getSession();
		session.removeAttribute(DefaultSessionKeys.USER_ID_KEY);
		session.removeAttribute(DefaultSessionKeys.USERNAME_KEY);
	}

	protected void applyUserLogin(FlowData flowData, UserDO resultUser) {
		HttpSession session = flowData.getSession();
		session.setAttribute(DefaultSessionKeys.USER_ID_KEY, resultUser.getId());
		session.setAttribute(DefaultSessionKeys.USERNAME_KEY, resultUser.getName());
	}
	
	protected void redirectForRequest(FlowData flowData) {
		String url = flowData.getParameters().getString(WebConstants.REDIRECT_PARAM_NAME);
		if (!StringUtil.isEmpty(url)) {
			// FIXME 注意判断跨域名跳转
			flowData.redirectTo(url);
		} else {
			flowData.redirectTo(defaultModule, defaultTarget);
		}
	}

	public void setUserAO(UserAO userAO) {
		this.userAO = userAO;
	}

}
